package com.zm.study.common;

import org.apache.commons.lang3.reflect.FieldUtils;

import java.lang.reflect.Field;

/**
 * 对象字段操作 仅用于日志操作
 * @author Joshua
 *
 */
public class ObjectFieldUtil {
	
	
	/**
	 * 读取对象字段为字符串记录
	 * @param cls
	 * @param model
	 * @return
	 */
	public static String readObjectsAsString(Class<?> cls, Object model){
		Field[]  fields = FieldUtils.getAllFields(cls);
		StringBuffer sb = new StringBuffer();
		int length = fields.length;
		for(int i = 0;i<length;i++){
			Field field = fields[i];
			try {
				Object v = FieldUtils.readField(field, model, true);
				Class<?> fieldType = field.getType();
				if(v!=null){
					if(fieldType.isPrimitive() || (v instanceof String) || isWrapClass(fieldType)){
						 sb.append(field.getName()).append(":").append(String.valueOf(v)).append(',');
					}
				}
				 
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		String ret = sb.toString();
		return ret.length()>1?ret.substring(0,ret.length()-1):ret;
	}
	
	public static boolean isWrapClass(Class clz) {
        try { 
           return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
        } catch (Exception e) {
            return false; 
        } 
    } 
	


}
